package il.ac.technion.cs236700.utils.composite;

import il.ac.technion.cs236700.utils.visitor.Action;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/** 
 * An implementation for the Composite Design Pattern - the Composite part
 * 
 * @authors Regev Azriel & Sharon Ronen
 *
 */
public class Composite<T> extends Component<T> {
	
	private ArrayList<Component<T>> children = new ArrayList<Component<T>>();
	
	public Composite(T data) {
		super(data);
	}

	public Composite(T data,Component<T> parent) {
		super(data,parent);
	}
	
	@Override
	public void add(Component<T> c) {
		children.add(c);
		c.setParent(this);
	}

	@Override
	public Component<T> getChild(int index) {
		return children.get(index);		
	}

	public List<Component<T>> getChildren(){
		return children;
	}
	
	@Override
	public boolean remove(Component<T> c) {
		boolean b = children.remove(c);
		if (b) c.setParent(null);
		return b;		
	}

	@Override
	public void visit(Action<T> action) {
		action.visit(this.data);
		for (Component<T> child : children) {
			child.visit(action);
		}
	}
	
	@Override
	public Component<T> search(Comparator<T> c,T arg) {		
		Component<T> $;
		if (c.compare(data, arg)==0) return this;
		for (Component<T> child : children) {
			if (($=child.search(c,arg))!=null) return $;
		}
		return null;
	}
}
